package com.itWaiLong.Service.Impl;

import com.itWaiLong.AppException.AppException;
import com.itWaiLong.AppException.GlobalExceptionHandler;
import com.itWaiLong.Dao.learning_resource;
import com.itWaiLong.Mapper.LearningMapper;
import com.itWaiLong.Service.LearningService;
import com.itWaiLong.Utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.List;
import java.util.Map;

@Service
public class LearningServiceImpl implements LearningService {

    @Autowired
    private LearningMapper learningMapper;

    /**
     * 添加学习资料
     * @param learningResource
     * @return
     */
    public void add(learning_resource learningResource) {

        //设置发布者的id
        Map<String, Object> map = ThreadLocalUtil.getThreadLocal();
        Integer userId = (Integer) map.get("userId");

        learningResource.setUploaderId(userId);

        //设置发布时间
        learningResource.setUploadTime(LocalDate.now());

        int result = learningMapper.add(learningResource);
        if (result < 0) {
            throw new GlobalExceptionHandler(AppException.TIAN_JIA_CHENG_GONG);
        }
    }

    @Override
    public void update(learning_resource learningResource) {

        //获取用户id
        Map<String, Object> map = ThreadLocalUtil.getThreadLocal();
        Integer userId = (Integer) map.get("userId");

        //设置用户id
        learningResource.setUploaderId(userId);

        int result = learningMapper.update(learningResource);
        if (result < 0) {
            throw new GlobalExceptionHandler(AppException.BIAN_JI_SHI_BAI);
        }
    }

    @Override
    public void delete(int resourceId) {

        int result = learningMapper.delete(resourceId);
        if (result < 0) {
            throw new GlobalExceptionHandler(AppException.SHAN_CHU_SHI_BAI);
        }
    }

    /**
     * 通过资料id查询资料
     * @param resourceId
     * @return
     */
    public learning_resource selectById(Integer resourceId) {

        learning_resource learningResource = learningMapper.selectById(resourceId);
        if (learningResource == null) {
            throw new GlobalExceptionHandler(AppException.MEI_YOU_SHU_JU);
        }
        return learningResource;
    }

    /**
     * 查询所有学习资料
     * @return
     */
    public List<learning_resource> selectAll() {
        List<learning_resource> list = learningMapper.selectAll();
        if (list == null || list.size() == 0) {
            throw new GlobalExceptionHandler(AppException.MEI_YOU_SHU_JU);
        }
        return list;
    }
}
